library('haven'); library('janitor')
recode99 <- function(x){
  x[x == 99] <- NA
  x
}

recode_nsnr <- function(x){
  x[x == "Não sabe / Não respondeu"| x == "NS/NR"] <- NA
  x
}

gen_labels <- function(x){
  as_factor(x)
#  forcats::as_factor((labelled(x, attr(x, "labels"))))
}

get_mode <- function(x){
  names(sort(table(x), decreasing = TRUE)[1])
}

impute <- function(x, block){
  if(is.character(x) == TRUE | is.factor(x) == TRUE){
    imputed <-  ave(x, block, FUN = get_mode)
  }
  if(is.numeric(x) == TRUE){
    imputed <- ave(x, block, FUN = mean, na.rm = TRUE)
    imputed[is.na(imputed)] <- mean(x, na.rm = TRUE)
  }
  x[is.na(x) | is.nan(x)] <- imputed[is.na(x) | is.nan(x)]
  x
}

factor2num <- function(x){
  as.numeric(as.character(x))
}


label_impute_nsnr <- function(x, crosstabs = TRUE, recode_nsnr = TRUE, factor2num = FALSE){
  x <- gen_labels(x)
  if(recode_nsnr == TRUE){
    x  <- recode_nsnr(x)
  }
  print(paste0("% NA to Impute: ", round(100 * mean(is.na(x) | is.nan(x))), "%"))
  x <- impute(x, panel1$codesetor)
  if(factor2num == TRUE){
    x <- factor2num(x)
  }
  if(crosstabs == TRUE){
    print((tabyl(x)))
  }
  x
}


label_nsnr <- function(x, crosstabs = TRUE, recode_nsnr = TRUE, factor2num = FALSE){
  x <- gen_labels(x)
  if(recode_nsnr == TRUE){
    x  <- recode_nsnr(x)
  }
  x <- droplevels(x)
  print(paste0("% NA: ", round(100 * mean(is.na(x) | is.nan(x))), "%"))
  if(factor2num == TRUE){
    x <- factor2num(x)
  }
  if(crosstabs == TRUE){
    print((tabyl(x)))
  }
  x
}
